package org.zoomdev.zoom.web.parameter.pre.impl;

import jakarta.servlet.http.HttpServletRequest;
import org.zoomdev.zoom.common.caster.Caster;
import org.zoomdev.zoom.web.action.ActionContext;
import org.zoomdev.zoom.web.parameter.PreParameter;
import org.zoomdev.zoom.web.parameter.PreParameterParser;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 可以接受没有contentType, contentType= www-form
 *
 * @author jzoom
 */
public final class FormPreParamParser implements PreParameterParser {

    public static class FormPreParameter implements PreParameter {

        private final HttpServletRequest request;
        private Map<String, Object> map;

        public FormPreParameter(HttpServletRequest request) {
            this.request = request;
        }

        @Override
        public Object get(String key) {
            return request.getParameter(key);
        }

        @Override
        public Set<String> getKeys() {
            Enumeration<String> names = request.getParameterNames();
            Set<String> set = new HashSet<>();
            while (names.hasMoreElements()) {
                set.add(names.nextElement());
            }
            return set;
        }

        @Override
        public Object getRaw() {
            return request;
        }

        @Override
        public Map<String, Object> getMap() {
            if (map == null) {
                map = Caster.to(request, Map.class);
            }
            return map;
        }
    }

    @Override
    public PreParameter preParse(ActionContext context) throws Exception {
        return new FormPreParameter(context.getRequest());
    }


}
